package com.zhouxianglh.week156;

import java.util.ArrayList;
import java.util.List;

public class Thrid {
    public static void main(String[] args) {
        System.out.println(removeDuplicates("abcd", 2));
        System.out.println(removeDuplicates("deeedbbcccbdaa", 3));
        System.out.println(removeDuplicates("pbbcggttciiippooaais", 2));
    }

    public static String removeDuplicates(String s, int k) {
        if (s.isEmpty() || s.length() < k) {
            return s;
        }
        List<Character> list = new ArrayList<>();
        for (char c : s.toCharArray()) {
            list.add(c);
        }
        boolean flag = true;
        while (flag) {
            flag = removeDuplicates(list, k);
        }
        StringBuilder str = new StringBuilder(list.size());
        for (Character c : list) {
            str.append(c);
        }
        return str.toString();
    }

    public static boolean removeDuplicates(List<Character> s, int k) {
        boolean result = false;
        int flag = 0;
        Character flagChar = null;
        for (int i = 0, j = s.size(); i < j; i++) {
            if (null == flagChar) {
                flagChar = s.get(i);
                flag = 1;
                continue;
            }
            //
            if (s.get(i).equals(flagChar)) {
                flag++;
                if (flag >= k) {
                    result = true;
                    int temp = flag;
                    while (temp > 0) {
                        s.remove(i);
                        temp--;
                        i--;
                    }
                    j = j - flag;
                    flag = 0;
                    flagChar = null;
                }
            } else {
                flag = 1;
                flagChar = s.get(i);
            }
        }
        return result;
    }
}
